package pixelradar.tasks;

import pixelradar.region.MwChunk;
import pixelradar.region.RegionManager;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;

public class SaveChunkTask extends Task {
    private static final HashMap<Long, SaveChunkTask> chunksUpdating = new HashMap<>();
    private MwChunk chunk;
    private RegionManager regionManager;
    private final AtomicBoolean Running = new AtomicBoolean();

    public SaveChunkTask(MwChunk chunk, RegionManager regionManager) {
        this.chunk = chunk;
        this.regionManager = regionManager;
    }

    public void run() {
        this.Running.set(true);
        this.chunk.write(this.regionManager.regionFileCache);
    }

    public void onComplete() {
        Long coords = this.chunk.getCoordIntPair();
        chunksUpdating.remove(coords);
        this.Running.set(false);
    }

    public boolean checkForDuplicate() {
        Long coords = this.chunk.getCoordIntPair();
        if (!chunksUpdating.containsKey(coords)) {
            chunksUpdating.put(coords, this);
            return false;
        } else {
            SaveChunkTask task2 = chunksUpdating.get(coords);
            if (!task2.Running.get()) {
                task2.updateChunkData(this.chunk, this.regionManager);
                return true;
            } else {
                chunksUpdating.put(coords, this);
                return false;
            }
        }
    }

    public void updateChunkData(MwChunk chunk, RegionManager regionManager) {
        this.chunk = chunk;
        this.regionManager = regionManager;
    }
}
